package com.lanou.service.imp;

import com.lanou.service.MQservice;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

@Service
public class MQserviceImpl implements MQservice {

    @Resource
    private JmsTemplate jmsTemplate ;


    @Override
    public void sendMessage(String msg) {

        // 发送消息

        MessageCreator messageCreator = new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        };

        jmsTemplate.send(messageCreator);

    }

    @Override
    public String receiveMsg() {

        //接受消息
        TextMessage message = (TextMessage) jmsTemplate.receive();

        if (message!=null){
            try {
                return message.getText();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
        return "没有消息";
    }
}
